import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;

public class StudentFileRepo implements StudentRepo {
    public static final String STU_LIST_TXT = "stuList.txt";
    private final ArrayList<Student> students = new ArrayList<>();

    public StudentFileRepo() throws IOException {
        // 在程序初始化时 读文件 将文件的内容加载到list中来
        // 之后的操作都是围绕着list进行的，不设及文件的读写
        BufferedReader reader = new BufferedReader(new FileReader(STU_LIST_TXT));
        String line;
        while ((line = reader.readLine()) != null && !line.isEmpty()) {
            String[] ss = line.split(" ");
            Student student = new Student();
            // 修改学生实体
            student.setStuNum(ss[0]);
            student.setClassName(ss[1]);
            student.setName(ss[2]);
            student.setSex(ss[3]);
            student.setAge(Integer.valueOf(ss[4]));
            students.add(student);
        }
        reader.close();
    }

    @Override
    public void newStudent(Student student) throws SQLException {
        students.add(student);
    }

    @Override
    public void deleteStudent(String stuNum1) {
        // 在学生列表中查找学生
        for (Student student : students) {
            // 根据学号来查询
            String stuNum = student.getStuNum();
            if (stuNum.equals(stuNum1)) {
                //查询到了要删除的学生
                students.remove(student);
                return;
            }
        }
    }

    @Override
    public void updateStudent(Student student) throws SQLException {
        Student student1 = this.findStudent(student.getStuNum());

        student1.setClassName(student.getClassName());
        student1.setName(student.getName());
        student1.setSex(student.getSex());
        student1.setAge(student.getAge());
    }

    public Student findStudent(String s) {

        // 在学生列表中查找学生
        for (Student student : students) {
            // 根据学号 或姓名 来查询
            String stuNum = student.getStuNum();
            String name = student.getName();
            if (stuNum.equals(s) || name.equals(s)) {
                return student;
            }
        }
        return null;
    }

    public void close() throws IOException {
        // 在程序退出前调用
        // 将list中的内容写入文件
        BufferedWriter writer = new BufferedWriter(new FileWriter(STU_LIST_TXT));
        for (Student student : students) {
            String s = student.getStuNum()
                    + " " + student.getClassName()
                    + " " + student.getName()
                    + " " + student.getSex()
                    + " " + student.getAge();
            writer.write(s);
            writer.newLine();
        }
        writer.close();
    }
}
